var definedemotions;
var emoticons,
    codesMap = {},
    primaryCodesMap = {},
    regexp,
    metachars = /[[\]{}()*+?.\\|^$\-,&#\s]/g,
    entityMap;

entityMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
    '/': '&#x2F;'
};

function escape(string) {
    return emreplace(string,/[&<>"'\/]/g, function(s) {
        return entityMap[s];
    });
}


/**
 * Replace emoticons in text.
 *
 * @param {String} text
 * @param {Function} [fn] optional template builder function.
 */
function emreplace(code,text, fn) {
    var name = codesMap[code];
    return tpl(name, code, definedemotions[name].title);
}

function getSmilyCode(str){
    
}

function emreplace(code,text, fn) {
    var name = codesMap[code];
    return tpl(name, code, definedemotions[name].title);
}
/**
 * Define emoticons set.
 *
 * @param {Object} data
 */
function define(data) {
    definedemotions=data;
    var name, i, codes, code,
        patterns = [];

    for (name in data) {
        codes = data[name].codes;
        for (i in codes) {
            code = codes[i];
            codesMap[code] = name;

            // Create escaped variants, because mostly you want to parse escaped
            // user text.
            codesMap[escape(code)] = name;
            if (i == 0) {
                primaryCodesMap[code] = name;
            }
        }
    }

    for (code in codesMap) {
        patterns.push('(' + emreplace(code,metachars, "\\$&") + ')');
    }

    //regexp = new RegExp(patterns.join('|'), 'g');
    emoticons = data;
}


/**
 * Get primary emoticons as html string in order to display them later as overview.
 *
 * @param {Function} [fn] optional template builder function.
 * @return {String}
 */
function toString(primaryCodesMapfv) {
    var code,
        str = '',
        name;

    for (code in primaryCodesMap) {
        name = primaryCodesMap[code];
        str += tpl(name, code, definedemotions[name].title);
    }

    return str;
};

/**
 * Build html string for emoticons.
 *
 * @param {String} name
 * @param {String} code
 * @param {String} title
 * @return {String}
 */
function tpl (name, code, title) {
    return '<span class="emoticon emoticon-' + name + '" title="' + title + '">' +
        code + '</span>';
};

